package utils;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class ImageUtils {

	public static byte[] imageToByteArray (ImageIcon i) {
		byte[] bytes = null;
		if (i!= null) {
			try {
				BufferedImage bufferedImage = new BufferedImage(i.getIconWidth(), i.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
				Graphics2D g2 = bufferedImage.createGraphics();
				g2.drawImage(i.getImage(), 0, 0, null);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ImageIO.write(bufferedImage, "jpg", baos);
				bytes = baos.toByteArray();
				baos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				StackTracePrinter.print(e);
			}
		}
		return bytes;
	}

	public static ImageIcon bytesToImage (byte[] bytes, String defaultImagePath) {
		if (bytes == null) {
			if (defaultImagePath != null)
				return new ImageIcon(ImageUtils.class.getResource(defaultImagePath));
			else
				return null;
		}
		return new ImageIcon(bytes);

	}

	public static void imageToDB(ImageIcon photo, PreparedStatement stmt, int parameterIndex)
			throws SQLException {
		byte[] bytes = ImageUtils.imageToByteArray (photo);
		if (bytes != null) {
			stmt.setBinaryStream(parameterIndex, new ByteArrayInputStream(bytes));
		} else {
			stmt.setNull(parameterIndex, Types.BINARY);
		}
	}
	
	public static ImageIcon resize (String imagePath, int width, int height) {
		return resize(new ImageIcon(imagePath), width, height);
	}
	
	public static ImageIcon resize (ImageIcon image, int width, int height) {
		return new ImageIcon(image.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH));
	}

}
